package dk.lector.domain;

import dk.lector.R;
import dk.lector.datasource.DBhelper;
import dk.lector.datasource.DocDBRepository;
import dk.lector.datasource.UserDBRepository;
import dk.lector.domain.entities.User;
import dk.lector.remote.TSMobileService;
import dk.lector.utils.TSProgressDialog;
import dk.lector.utils.TScrypto;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

public class UserFacade {
	
	private static final String TAG = UserFacade.class.getSimpleName();

	public static void login(final Context appContext, final String username,
			final String password) {
		
		final Intent broadcastIntent = new Intent(
				"ts.core.action.LOGIN_RESULT");
		
		AsyncTask<Void, Void, Void> loginTask = new AsyncTask<Void, Void, Void>() {
			
			@Override
			protected void onPreExecute() {
				TSProgressDialog.showDialog(appContext,
						R.string.login_pleaseWait_text);
				super.onPreExecute();
			}
			
			@Override
			protected Void doInBackground(Void... nothing) {

				String CipherUsername = TScrypto.encrypt(appContext, username);
				String CipherPassword = TScrypto.encrypt(appContext, password);
				
				User user = UserDBRepository.cacheUser(appContext,
						TSMobileService.login(appContext, CipherUsername, CipherPassword));
				boolean result = false;
				if (user != null){
					result = true;
				}
				

				broadcastIntent.putExtra("result", result);
				
				
				return null;
			}
			@Override
			protected void onPostExecute(Void result) {
				TSProgressDialog.dismissDialog();
				appContext.sendBroadcast(broadcastIntent);
				super.onPostExecute(result);
			}


		};
		
		loginTask.execute();
	}


	public static void logOut(final Context appContext) {
	AsyncTask<Void, Void, Void> logoutTask = new AsyncTask<Void, Void, Void>() {
			
			@Override
			protected void onPreExecute() {
				TSProgressDialog.showDialog(appContext,
						R.string.logout_pleaseWait_text);
				super.onPreExecute();
			}
			
			@Override
			protected Void doInBackground(Void... nothing) {
			
				DocDBRepository.deleteFavorites(appContext);
				UserDBRepository.deleteUser(appContext);
				
				return null;
			}
			@Override
			protected void onPostExecute(Void result) {
				TSProgressDialog.dismissDialog();
				super.onPostExecute(result);
			}


		};
		
		logoutTask.execute();
	}

}